package spring.security.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import com.fasterxml.jackson.annotation.JsonView;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import spring.security.dto.PageList;
import spring.security.dto.User;
import spring.security.entity.SysUser;
import spring.security.req.UserReq;
import spring.security.service.UserService;
import spring.security.util.IDGenerator;

@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private ProviderSignInUtils providerSignInUtils;
	
	@PostMapping("/regist")
	public void regist(@RequestBody @Valid SysUser user, HttpServletRequest request) {
		String userId = user.getUsername();
		
		providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
	}
	
	//getCurrentUser1和getCurrentUser2是相同效果的
	@GetMapping("/getCurrentUser1")
	public Object getCurrentUser1() {
		return SecurityContextHolder.getContext().getAuthentication();
	}
	
	@GetMapping("/getCurrentUser2")
	public Object getCurrentUser2(Authentication auth) {
		return auth;
	}
	//只获取用户信息
	@GetMapping("/getCurrentUser3")
	public Object getCurrentUser3(@AuthenticationPrincipal UserDetails user) {
		return user;
	}
	
	@GetMapping
	@JsonView(User.UserSimpleView.class)
	public List<User> query(UserReq req, @PageableDefault(page = 2, size = 15, sort = "age,desc") Pageable page) {
		System.out.println(ReflectionToStringBuilder.toString(req, ToStringStyle.MULTI_LINE_STYLE));

		System.out.println(page.getPageSize());
		System.out.println(page.getPageNumber());
		System.out.println(page.getSort());

		List<User> userList = new ArrayList<>();
		userList.add(new User());
		userList.add(new User());
		userList.add(new User());
		return userList;
	}

	@GetMapping("/{id:\\d+}")
	@ApiOperation("用户查询方法")
	public PageList<List<SysUser>> get(@ApiParam("用户ID") @PathVariable() String id) {
		PageList<List<SysUser>> info = userService.getInfo();
		// throw new UserNullException(id);
		return info;
		/*
		 * User user = new User(); user.setUserName("xiaxin"); user.setBirthDay(new
		 * Date()); return user;
		 */
	}

	@PostMapping
	public SysUser insert(@RequestBody @Valid SysUser user) {
		System.out.println(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE));
		user.setPkid(IDGenerator.getDefaultUUID());
		userService.insert(user);
		return user;
	}

	@PutMapping("/{id:\\d+}")
	public User update(@RequestBody @Valid User user, BindingResult errors) {
		if (errors.hasErrors()) {
			List<ObjectError> allErrors = errors.getAllErrors();
			allErrors.stream().forEach(err -> {
				FieldError fieldError = (FieldError) err;
				String error = fieldError.getField() + " : " + fieldError.getDefaultMessage();
				System.out.println(error);
			});
		}

		System.out.println(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE));
		user.setId("1");
		return user;
	}

	@DeleteMapping("/{id:\\d+}")
	public void delete(@PathVariable() String id) {
		System.out.println(id);
	}

}
